/**
 * author:xing
 * 调用示例:$.simpleTip(tipHtml,undo);
 * {String}tipHtml,
 * {Boolean}undo
 * 
 */
(function($){
	$.extend({
		simpleTip:function(tipHtml,undo){
			var o={
				tipHtml:tipHtml,
				undo:undo
			}
			return Tip.init(o);
		}
	});
	var Tip={
		init:function(o){
			var d=$('<div/>').css({
				'background':'#f58f4d',
				position:'absolute',
				top:3,
				padding:'2px 5px'
			}).attr('id','simpleTip').addClass('r3');
			d.html(o.tipHtml);
			if(o.undo){
				var undo=$('<span/>').addClass('tipCancel').html('撤销');
				d.append(undo);
			}
			$(document.body).append(d);
			d.css('left',(document.documentElement.clientWidth-d.width())/2);
			setTimeout(this.destory,5000);
		},
		destory:function(){
			$('#simpleTip').remove();
		}
	}
	
})(jQuery);



/**
 * simpleForm gexing
 * @param {Object} options
 */
(function($) {
  $.fn.simpleForm = function(options) {
	options = options || {}; 
	var defaultOpt = { 
		checkboxCls   	: options.checkboxCls || 'xq-checkbox' , radioCls : options.radioCls || 'xq-radio' ,	
		checkedCls 		: options.checkedCls  || 'xq-checked'  , selectedCls : options.selectedCls || 'xq-selected' , 
		hideCls  	 	: 'xq-hide'
	};
    return this.each(function() {
    	var $this = $(this);
    	var wrapTag = $this.attr('type') == 'checkbox' ? '<div class="'+defaultOpt.checkboxCls+'">' : '<div class="'+defaultOpt.radioCls+'">';
    	// for checkbox
    	if( $this.attr('type') == 'checkbox') {
    		
			$.form.makeCheckbox($this,wrapTag,defaultOpt);
    	
		} 
    	else if( $this.attr('type') == 'radio') {

    		$.form.makeRadio($this,wrapTag,defaultOpt);
    	}
		else if( $this.is('select') ){
		
		    $.form.makeSelect();
		}
    });
  }
  $.form={
	 makeCheckbox:function(el,wrapTag,defaultOpt){
	 		var elParent=el.parent();
	 		if(!elParent.is('div.xq-checkbox,div.xq-checked')){
				//elParent.replaceWith(elParent.html());
				el.wrap(wrapTag);
			}
			el.addClass(defaultOpt.hideCls).change(function() {
    			if( $(this).is(':checked') ) { 
    				$(this).parent().addClass(defaultOpt.checkedCls); 
    			} 
    			else { $(this).parent().removeClass(defaultOpt.checkedCls); 	}
    		});
    		
    		if( el.is(':checked') ) {
				el.parent().addClass(defaultOpt.checkedCls);    		
    		}else{
				el.parent().removeClass(defaultOpt.checkedCls);    	
			}
		
	 },
	 makeRadio:function(el,wrapTag,defaultOpt){
			el.addClass(defaultOpt.hideCls).wrap(wrapTag).change(function() {
    			//radioֻ����һ��
   				$('input[name="'+$(this).attr('name')+'"]').each(function() {
   	    			if( $(this).is(':checked') ) { 
   	    				$(this).parent().addClass(defaultOpt.selectedCls); 
   	    			} else {
   	    				$(this).parent().removeClass(defaultOpt.selectedCls);     	    			
   	    			}
   				});
    		});
    		
    		if( el.is(':checked') ) {
				el.parent().addClass(defaultOpt.selectedCls);    		
    		}    		
	 }
  }
})(jQuery);
/**
 * @author xing
 * @copyright GZbugu
 */
(function($){
    $.fn.simplePage = function(os){
        var options = {
            pager: '.pager',//表格控件的容器
            container: '.tableData',//放置表格数据的容器
            form: '#form',//放置查询条件的表单
            pageForm: '#pageForm',//放置隐藏与的Div
            url: '',//发送请求的地址
            success: null,//成功后执行的回调函数
            currentPage: 1,
            pageSize: 15,
            callbacks: null,
            hoverClass: 'tdHover',
            param: {},//附加参数
            type: null,//可选：action,
            pageStyle: 'line',//slide//click
            pageShow: 8,
            fixedH: 200,
            fixed: true,
            width: '',
            dataType: 'html'
            //pageUpdate:false//是否更新的依据,私有属性
        };
        var o = $.extend(options, os);
        return this.each(function(){
            o.pager = $(this).find(o.pager);
            o.pager.find('a.go').html('确 定');
            o.container = $(this).find(o.container);
            //	o.container.height(o.fixedH).css({
            //	overflowX:'hidden',
            //	overflowY:'auto'
            //	});

            //首先清除click事件
            o.pager.unbind('click');
			$('div.line').unbind('click');
            //	console.log(o);
		//	$(o.form).hide();
            $('div.line').click(function(){
                if ($(o.form).is(':hidden')) {
                    $(o.form).slideDown();
                }
                else {
                    $(o.form).slideUp();
                }
            });
            $('p.tips').ajaxStart(function(){
                $(this).fadeIn('fast');
            });
            $('p.tips').ajaxComplete(function(){
                $(this).fadeOut('fast');
            });
            if (o.type == 'action') {
                //指定的动作，比如删除时的事件，这时需要在当前页刷新数据
                o.currentPage = $.page.getPage(o);
                o.pageSize = $.page.getPerp(o);
                $.page.setPage(o);
                return;
            }
            $.page.setPage(o);
            if (o.pageStyle == 'click') {
                $.page.handler(o);
            }
            else
                if (o.pageStyle == 'line') {
                    $.line.handleQueryLine(o);
                }
        })
    }
    /**
     * @classDescription 执行line模式下的逻辑代码
     * @param {Object} totalPage
     * @param {Object} o
     */
    $.line = {
        setLine: function(totalPage, o){
            for (var i = 0; i < totalPage; i++) {
                var a = $('<a/>').html('<span>' + (i + 1) + '</span>').addClass('pageA').bind('click', function(){
                    var s = $(this);
                    s.siblings().removeClass('pageActive');
                    s.addClass('pageActive');
                    o.currentPage = s.text();
                    $.page.loadData(o);
                });
                if (o.currentPage == i + 1) {
                    a.addClass('pageActive');
                }
                o.pager.append(a);
            }
            var limit = this.getLimit(o, totalPage);
			//console.log(limit);
            var aPage = o.pager.find('a.pageA').not('a.previous,a.nextAll,a.record');
            aPage.hide();
			
            aPage.slice(limit.start, limit.end).show();
            var prev = $('<a/>').html('<span>上一页</span>').addClass('pageA previous').unbind('click').bind('click', function(){
                var pageActive = o.pager.find('a.pageActive');
                var s = $(this);
                if (pageActive.prev().text() == '上一页') {
                    //alert('已经是第一页!');
                    return false;
                }
                pageActive.removeClass('pageActive');
                pageActive.prev().addClass('pageActive');
                o.currentPage = pageActive.prev().text();
                $.page.loadData(o);
            });
            var next = $('<a/>').html('<span>下一页</span>').addClass('pageA nextAll').unbind('click').bind('click', function(){
                var pageActive = o.pager.find('a.pageActive');
                var s = $(this);
                if (pageActive.next().text() == '下一页') {
                    //alert('已经是最后一页!');
                    return false;
                }
                pageActive.removeClass('pageActive');
                pageActive.next().addClass('pageActive');
                o.currentPage = pageActive.next().text();
                $.page.loadData(o);
            });
            var pageActiveText = o.pager.find('a.pageActive').text();
            var record = $('<a/>').html('<span>' + pageActiveText + '/' + totalPage + '</span>').addClass('pageA record');
            o.pager.prepend(prev).prepend(record).append(next);
        },
        handleQueryLine: function(o){
            $(o.form).find(".query").click(function(){
                //$(o.pageForm).append($(o.form).clone(true));
                $(o.pageForm).empty();
                $(o.form).find('input[type="text"]').each(function(){
                    var vals = $(this).val();
                    var s = $(this).clone().val(vals);
                    $(o.pageForm).append(s);
                });
                $(o.form).find('select').each(function(){
                    var vals = $(this).val();
                    var s = $(this).clone().val(vals);
                    $(o.pageForm).append(s);
                });
                //需要更新页码
                //o.pageUpdate=true;
                $.page.query(o);
            });
        },
        getLimit: function(o, totalPage){
            var start = parseInt(o.pager.find('a.pageActive').text());
            start = parseInt(start - o.pageShow / 2) < 0 ? 0 : parseInt(start - o.pageShow / 2);
            if (start + o.pageShow > totalPage) {
                start = totalPage - o.pageShow<0 ? 0:totalPage - o.pageShow ;
            }
            var end = (start + o.pageShow) > totalPage ? totalPage : start + o.pageShow;
            return {
                start: start,
                end: end
            }
        }
    };
    /**
     * @classDescription 执行click模式下的逻辑代码
     * @param {Object} o
     */
    $.page = {
        setPage: function(o){
            $(o.pageForm).hide();
            o.pager.find('input.page').val(o.currentPage);
            o.pager.find('input.perpage').val(o.pageSize);
            this.loadData(o);
        },
        getPage: function(o){
            if (o.pageStyle == "click") {
                var p = o.pager.find("input.page").val();
                return p;
            }
            else
                if (o.pageStyle == "line") {
                    var p = o.pager.find("a.pageActive").text();
                    return p;
                }
                else {
                    return o.currentPage;
                }
        },
        getLastPage: function(o){
            var lps = o.pager.find("code").text();
            var lastP = parseInt(lps);
            return lastP;
        },
        getPerp: function(o){
            if (o.pageStyle == "click") {
                var perp = o.pager.find("input.perpage").val();
                return perp;
            }
            else
                if (o.pageStyle == "line") {
                    return o.pageSize;
                }
        },
        genData: function(o){
            var pdata = $.extend({}, {
                "currentPage": o.currentPage,
                "pageSize": o.pageSize
            }, o.param);
            var sdata = $.extend({}, pdata, $.jsonObj(o.pageForm));
            //	console.log(sdata);
            return sdata;
        },
        loadData: function(o){
            var that = this;
            var data = that.genData(o);
            $.ajax({
                url: o.url,
                data: data,
                /*{
                 currentPage: o.currentPage,
                 pageSize: o.pageSize
                 },*/
                type: 'post',
                dataType: o.dataType,
                cache: false,
                success: function(result){
                    if ($(result).find("#noSession").val() == "noSession101") {
                        alert("系统登陆超时，请重新登陆！")
                        top.window.location.href = "../../../oa/login.jsp";
                    }
                    else {
						if ($.isFunction(o.success)) {
                        o.success(result);
                    }
                        if (o.dataType == "html") {
                            var res = $(result).find('tbody').html();
                            if ($(result).find('tbody tr').length < 1) {
                                var lengths = o.container.find('th').length;
                                o.container.find('tbody').html('<tr><td colspan="' + lengths + '"><span class="alert">没有需要显示的数据！</span></td></tr>');
                                //赋值总页数
                                var codeval = $(result).find('input:hidden').eq(0).val();
                                var code = o.pager.find('code');
                                code.text(codeval);
                                //赋值当前页
                                var currentPage = $(result).find('input:hidden').eq(1).val();
                                // console.log(currentPage);
                                o.pager.find('input.page').val(currentPage);
                            }
                            else {

                                o.container.find('tbody').html(res);
                                that.checkboxEvent(o);
                                that.tdClickEvent(o);
								that.hover(o);
								that.oddEven(o);
                                $('body').find('#totalPage').html($(result).find('input:hidden').eq(2).val());
                                if (o.pageStyle == 'click') {
                                    //赋值总页数
                                    var codeval = $(result).find('#totalPage').val();
                                    var code = o.pager.find('code');
                                    code.text(codeval);
                                    //赋值当前页
                                    var currentPage = $(result).find('#currentPage').val();
                                    // console.log(currentPage);
                                    o.pager.find('input.page').val(currentPage);
                                   
                                    if (typeof o.callbacks == "function") {
                                        o.callbacks();
                                    }
                                }
                                else
                                    if (o.pageStyle == 'line') {
                                        var totalPage = $(result).find('#totalPage').val();
                                        var currentPage = $(result).find('#currentPage').val();
                                        o.currentPage = currentPage;
                                        if (o.pager.find('a').length < 1) {
                                            $.line.setLine(totalPage, o);
                                        }
                                        //查询更新页码
                                        //	if(o.pageUpdate==true){
                                        o.pager.empty();
                                        $.line.setLine(totalPage, o);
                                    //	}
                                    }
                            }
                        }
                        else {
                            var data = result[0].data;
                            var isSuccess = result[0].isSuccess;
                            var totalPage = result[0].totalPage;
                            var currentPage = result[0].currentPage;
                            var totalCount = result[0].totalCount;
							$('body').find('#totalPage').html(totalCount);
                            o.container.find('tbody').html(data);
                            that.checkboxEvent(o);
                            that.tdClickEvent(o);
							that.hover(o);
							that.oddEven(o);
                            o.currentPage = currentPage;
                            if (o.pager.find('a').length < 1) {
                                $.line.setLine(totalPage, o);
                            }
                            o.pager.empty();
                            $.line.setLine(totalPage, o);
                            //o.container.find('tbody').html('<tr><td colspan="' + lengths + '"><span class="alert">没有需要显示的数据！</span></td></tr>');
                        }
                    }
                },
                error: function(){
                   	$.simpleTip('服务器繁忙，请重新登录再试！');
                }
            })
        },
        handler: function(o){
            var that = this;
            o.pager.find('.pager_first').bind('click', function(){
                //  o.form = o.pageForm;
                o.currentPage = 1;
                o.pageSize = that.getPerp(o);
                that.setPage(o);
            });
            o.pager.find('.pager_last').bind('click', function(){
                // o.form = o.pageForm;
                o.currentPage = that.getLastPage(o);
                o.pageSize = that.getPerp(o);
                /*if (o.currentPage == lastP) {
                 return;
                 }*/
                that.setPage(o);
            });
            o.pager.find(".pager_prev").click(function(){
                // o.form = o.pageForm;
                o.pageSize = that.getPerp(o);
                var p = that.getPage(o);
                o.currentPage = p - 1;
                if (o.currentPage <= 0) {
                    o.currentPage = 1;
                    return;
                }
                that.setPage(o);
            });
            o.pager.find(".pager_next").click(function(){
                //  o.form = o.pageForm;
                o.pageSize = that.getPerp(o);
                var pag = that.getPage(o);
                var _p = parseInt(pag);
                o.currentPage = _p + 1;
                var tot = parseInt(o.pager.find(".input_page").find("code").text());
                if (o.currentPage > tot) {
                    o.currentPage = tot;
                    return;
                }
                that.setPage(o);
            });
            o.pager.find(".go").click(function(){
                $.page.query(o);
            });
            $(o.form).find(".query").click(function(){
                //$(o.pageForm).append($(o.form).clone(true));
                $(o.pageForm).empty();
                $(o.form).find('input[type="text"]').each(function(){
                    var vals = $(this).val();
                    var s = $(this).clone().val(vals);
                    $(o.pageForm).append(s);
                });
                $(o.form).find('select').each(function(){
                    var vals = $(this).val();
                    var s = $(this).clone().val(vals);
                    $(o.pageForm).append(s);
                });
                $.page.query(o);
            });
            o.pager.keyup(function(e){
                var e = e || window.event;
                if (e.keyCode == '13') {
                    $.page.query(o);
                }
            })
        },
        hover: function(o){
            o.container.find("tr").hover(function(){
                $(this).find('td').addClass('tdHover');
            }, function(){
                $(this).find('td').removeClass('tdHover');
            });
        },
		oddEven:function(o){
			$('tr:odd').find('td').addClass('tdOdd');
			$('tr:even').find('td').addClass('tdEven');
		},
        query: function(o){
            var that = this;
            o.pageSize = that.getPerp(o);
            var pag = that.getPage(o);
            var total = parseInt(o.pager.find('code').text());
            if (parseInt(pag) > total) {
                o.currentPage = that.getLastPage(o);
            }
            else {
                o.currentPage = parseInt(pag);
            }
            that.setPage(o);
        },
        checkboxEvent: function(o){
            o.container.find('tr').each(function(i){
                //console.log(o.container.find('tr').length)
                var s = $(this);
                var checkbox = $('<input/>').attr({
                    type: 'checkbox'
                });
                var th = $("<th/>");
                var td = $('<td/>');
                if (i == 0) {
                    if (s.find('input:checkbox').is(':checkbox')) {
                        return;
                    }
                    th.append(checkbox).append('<label for="allcheck"></label>').prependTo(s);
                    checkbox.attr('id', 'allcheck').bind('change', function(){
                        var allCheckbox = o.container.find('tbody').find('input:checkbox');
                        if ($(this).attr('checked') == true) {
                            allCheckbox.attr('checked', 'checked');
                            allCheckbox.end().find('td').addClass('tdClick');
							//css('background', '#EEF6FF');
							allCheckbox.simpleForm();
                        }
                        else {
                            allCheckbox.attr('checked', '');
                            allCheckbox.end().find('td').removeClass('tdClick');
							allCheckbox.simpleForm();
                        }
                    });
                }
                else {
                    td.append(checkbox).prependTo(s);
                }
            });
            o.container.find('tbody input[type="checkbox"]').each(function(){
                $(this).change(function(e){
                    e.stopPropagation();
                    var self = $(this);
                    if (self.attr('checked') == true) {
                        self.parent().parent().find('td').addClass('tdClick');
                    }
                    else {
                        self.parent().parent().find('td').removeClass('tdClick');
                    }
					self.simpleForm();
                });
            });
			//定制元素
			$('input').simpleForm();
            if (o.width != null) {
                o.container.find('th').each(function(i){
                    $(this).width(o.width[i]);
                });
            }
        },
        tdClickEvent: function(o){
            o.container.find('tbody tr').each(function(){
                $(this).find('td').not(':eq(0)').click(function(){
                    var checkbox = $(this).parent().find('input:checkbox');
                    if (checkbox.attr('checked') == true) {
                        checkbox.attr('checked', '');
                        $(this).parent().find('td').removeClass('tdClick');
						
                    }
                    else {
                        checkbox.attr('checked', 'checked');
                        $(this).parent().find('td').addClass('tdClick');
                    }
					checkbox.simpleForm();
                });
            });
        }
    };
	//public method
	$.extend({
		jsonObj:function(form){
			 //判断是否有序列化的东东
        if (!$(form).html() || $(form).html() == null || $.trim($(form).html()) == "") {
            return null;
        }
        var formEl = $(form).find('input[type="text"]');
        var formselect = $(form).find('select');
		var formTextarea=$(form).find('textarea');
        var json = "{";
        for (var i = 0; i < formEl.length - 1; i++) {
            var name = formEl.eq(i).attr('name');
            var val = "'" + formEl.eq(i).val() + "'";
            json += name;
            json += ":";
            json += val;
            json += ",";
        }
        var lname = formEl.eq(formEl.length - 1).attr('name');
        var lval = "'" + formEl.eq(formEl.length - 1).val() + "'";
        json += lname;
        json += ":";
        json += lval;
        if (formselect) {
            json += ",";
            for (var i = 0; i < formselect.length - 1; i++) {
                var name = formselect.eq(i).attr('name');
                var val = "'" + formselect.eq(i).val() + "'";
                json += name;
                json += ":";
                json += val;
                json += ",";
            }
            var lname = formselect.eq(formselect.length - 1).attr('name');
            var lval = "'" + formselect.eq(formselect.length - 1).val() + "'";
            json += lname;
            json += ":";
            json += lval;
        }
		if(formTextarea){
			json+=",";
			for(var i=0;i<formTextarea.length-1;i++){
				var name=formTextarea.eq(i).attr('name');
				var val="'"+formTextarea.eq(i).val()+"'";
				json+=name;
				json+=":";
				json+=val;
				json+=",";
			}
			 var lname = formTextarea.eq(formTextarea.length - 1).attr('name');
            var lval = "'" + formTextarea.eq(formTextarea.length - 1).val() + "'";
            json += lname;
            json += ":";
            json += lval;
		}
        json += "}";
        var jsonObj = eval("(" + json + ")")
        return jsonObj;
		}
	});
})(jQuery);

